﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Web.Course;
using Telerik.WebControls;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Common.Upload;

public partial class sysadmin_CourseManager_UploadResource :PowerCreator.LMS.Web.Base.WebBasePage
{
    Course opCourse = new Course();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            ViewState["CourseID"] = Request.QueryString["CourseID"].ToString();
            InitPage();
            BinderCourse();
            BinderSysResourceType();

            BuildDirectory();
        }
    }

    protected override void InitPage()
    {
        lbl_InfoTitle.Text = GetLanageValueByKey("lbl_UploadResource_InfoTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Course.Text = GetLanageValueByKey("lbl_UploadResource_Course", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_ResourceType.Text = GetLanageValueByKey("lbl_UploadResource_ResourceType", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewDirectiory.Text = GetLanageValueByKey("lbl_UploadResource_NewDirectiory", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_File.Text = GetLanageValueByKey("lbl_UploadResource_File", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_UploadFile.Text = GetLanageValueByKey("btn_UploadResource_UploadFile", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_Back.Text = GetLanageValueByKey("btn_UploadResource_Back", PowerCreator.LMS.Language.LanagetItemType.Page);

        lbl_Description_title.Text = GetLanageValueByKey("lbl_UploadResource_Description_title", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Description_1.Text = GetLanageValueByKey("lbl_UploadResource_Description_1", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Description_2.Text = GetLanageValueByKey("lbl_UploadResource_Description_2", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Description_3.Text = GetLanageValueByKey("lbl_UploadResource_Description_3", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Description_4.Text = GetLanageValueByKey("lbl_UploadResource_Description_4", PowerCreator.LMS.Language.LanagetItemType.Page);

        base.InitPage();
    }
    private void BinderCourse()
    {
        DataTable dt = new DataTable();
        string search = "";
        dt = opCourse.Query(search);
        ddl_Course.DataSource = dt;
        ddl_Course.DataTextField = "CourseName";
        ddl_Course.DataValueField = "Course_Id";
        ddl_Course.DataBind();
        for (int i = 0; i < ddl_Course.Items.Count; i++)
        {
            if (ddl_Course.Items[i].Value == ViewState["CourseID"].ToString())
            {
                ddl_Course.Items[i].Selected = true;
                return;
            }
        }
        //ddl_Course.SelectedIndex = 0;
    }
    private void BinderSysResourceType()
    {
        ListItem li2 = new ListItem();
        li2.Text = GetLanageValueByKey("Resource_Type2", PowerCreator.LMS.Language.LanagetItemType.Page);
        li2.Value = "2";
        ddl_ResourceType.Items.Insert(0, li2);
        ListItem li3 = new ListItem();
        li3.Text = GetLanageValueByKey("Resource_Type3", PowerCreator.LMS.Language.LanagetItemType.Page);
        li3.Value = "3";
        ddl_ResourceType.Items.Add(li3);
        ListItem li4 = new ListItem();
        li4.Text = GetLanageValueByKey("Resource_Type4", PowerCreator.LMS.Language.LanagetItemType.Page);
        li4.Value = "4";
        ddl_ResourceType.Items.Add(li4);
        ListItem li5 = new ListItem();
        li5.Text = GetLanageValueByKey("Resource_Type5", PowerCreator.LMS.Language.LanagetItemType.Page);
        li5.Value = "5";
        ddl_ResourceType.Items.Add(li5);
        //ListItem li6 = new ListItem();
        //li6.Text = GetLanageValueByKey("Resource_Type1", PowerCreator.LMS.Language.LanagetItemType.Page);
        //li6.Value = "1";
        //ddl_ResourceType.Items.Add(li6);
    }
    private void BuildDirectory()
    {
        txt_NewDirectiory.Text = opCourse.GetUploadDirectoryByCourseID(int.Parse(ddl_Course.SelectedValue.ToString()), opCourse.GetSysResourceTypeByValue(int.Parse(ddl_ResourceType.SelectedValue.ToString())));
    }
    
    //检查上传文件类型
    public bool IsUploadFileType(string extension)
    {
        string allowExtensions = "";    //允许上传的类型
        if (Convert.ToInt16(SysResourceType.PowerCreator) == int.Parse(ddl_ResourceType.SelectedValue.ToString()))
        {
            allowExtensions = "rar|zip|";
            if (!opCourse.IsAllowedExtension(extension, allowExtensions))
            {
                lbl_FileUpload_msg_FileType.Text = GetLanageValueByKey("UploadResource_msg_m2", PowerCreator.LMS.Language.LanagetItemType.Page) + allowExtensions;
                return false;
            }
        }
        else if (Convert.ToInt16(SysResourceType.Video) == int.Parse(ddl_ResourceType.SelectedValue.ToString()))
        {
            allowExtensions = "asf|rmvb|wmv|";
            if (!opCourse.IsAllowedExtension(extension, allowExtensions))
            {
                lbl_FileUpload_msg_FileType.Text = GetLanageValueByKey("UploadResource_msg_m1", PowerCreator.LMS.Language.LanagetItemType.Page) + allowExtensions;
                return false;
            }
        }
        return true;
    }
    protected void btnUploadFile_Click(object sender, EventArgs e)
    {
        btn_UploadFile.Enabled = false;
        foreach (UploadedFile file in RadUploadContext.Current.UploadedFiles)
        {
            string Path = Server.MapPath(WebUtils.WebRoot + "/" + txt_NewDirectiory.Text + "/");

            //如果路径不存在，则创建
            if (System.IO.Directory.Exists(Path) == false)
            {
                System.IO.Directory.CreateDirectory(Path);
            }
            
            string filetype = file.GetExtension();
            if (!IsUploadFileType(filetype)) return;
            
            //组合路径，file.GetName()取得文件名
            string fileName = opCourse.GetUploadResourceFileName(file.GetExtension());

            Path = Path + fileName;

            //保存
            file.SaveAs(Path, true);

            //是否解压
            if (ddl_ResourceType.SelectedValue.ToString() == "1")
            {
                
                Upload.WinRarFile(Path);
            }
            string url = "AddResourceInfo.aspx?AddResourceType=upload&CourseID=" + ddl_Course.SelectedValue.ToString() + "&SysResourceType=" + ddl_ResourceType.SelectedValue.ToString() + "&dir=" + txt_NewDirectiory.Text.ToString() + "&fileName=" + fileName + "&fullpath=" + Path;
            Script.RedirectURL(url);
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string url = "CourseResource.aspx";
        Script.RedirectURL(url);
    }
    //protected void btnUploadFile_Click(object sender, EventArgs e)
    //{
    //    if (string.IsNullOrEmpty(txtNewDirectiory.Text.Trim()))
    //    {
    //        Script.Alert(Page, "upload", "资源文件夹名称不能为空!");
    //        return;
    //    }
    //    //开始上传文件       
    //    string path = "";       
    //    if (!CheckUploadFile()) return;
    //    if (!CheckNewFoladerName(txtNewDirectiory.Text)) return;
    //    try
    //    {            
    //        //考虑是否不同的文件夹类型采用不同的检查方式
    //        HttpPostedFile hpf = flResource.PostedFile;

    //        string ucn = "", up = "", urt = "", und = "", ufn = "",ucnid="";         //url参数

    //        int courseid = int.Parse(ddlCourse.SelectedValue);
    //        ucnid = courseid.ToString();
    //        ucn = ddlCourse.Items[ddlCourse.SelectedIndex].Text;

    //        int savedirectory = 0;                                                  //确定文件夹后缀名
    //        int resourcetypeid = int.Parse(ddlResourceType.SelectedValue);            
    //        savedirectory = GetWorked(resourcetypeid);
    //        urt = resourcetypeid.ToString();

    //        #region 返回该课程下的虚拟目录路径
            
            
    //        PowerCreator.LMS.Model.Entity.CourseInfo cinfo = new PowerCreator.LMS.Model.Entity.CourseInfo();
    //        cinfo = courseManager.Load(courseid);

    //        PowerCreator.LMS.Model.Entity.VirtualDirectoryInfo vinfo = new PowerCreator.LMS.Model.Entity.VirtualDirectoryInfo();
    //        vinfo = virtualManager.Load(cinfo.VirtualDirectoryID);

    //        #endregion           
            
    //        //string virDicertory = courseManager.GetCourseVirectoryPath(courseid);   //虚拟目录
    //        string virDicertory = vinfo.DirectoryName;
    //        if (!virDicertory.EndsWith("/"))
    //        {
    //            virDicertory += "/";
    //        }

    //        //使用了配置节点中的IIS路径，如果出现不至的情况，将会出现意外
    //        path = vinfo.DirectoryPath;
    //        if (path.EndsWith("\\"))
    //        {
    //            path += "\\";
    //        }

    //        string virNewPath = courseManager.CreatedDirectory(courseid,savedirectory);
    //        if (!virNewPath.EndsWith("/"))
    //            virNewPath += "/";

    //        up = virNewPath;
    //        und = txtNewDirectiory.Text;

    //        string fileName = GetFileName(hpf);

    //        //path = Server.MapPath(virDicertory);
    //        if (!path.EndsWith("\\"))
    //            path += "\\";

    //        path += virNewPath + "\\" + txtNewDirectiory.Text;
    //        path = path.Replace("/", "\\");

    //        WriteLog(path + "$$"+fileName);

    //        if (savedirectory == 1)
    //        {                
                //PowerCreator.LMS.Logic.Common.FileUploaded.SaveFile(hpf, path, fileName, true);
    //            fileName = ConfigurationManager.AppSettings["CourseDefaultFile"].ToString();
    //        }
    //        else
    //        {                
    //            fileName = GetFileName(hpf);
    //            //创建一个新的文件名称
    //            fileName = "File_" + Guid.NewGuid().ToString() + "." + GetFileExtension(fileName);
    //            FileUploaded.SaveFile(hpf,path,fileName,false);
    //        }

    //        ufn = fileName;
    //        //cn=CourseName,rt=ResourceTypeID, p=文件夹存放路径, fn=FileName,nd=资源存储文件夹名称
    //        string url = string.Format("{6}?cnid={0}&cn={1}&rt={2}&p={3}&nd={4}&fn={5}&pn=upload", Base64.Encode(ucnid), Base64.Encode(ucn), Base64.Encode(urt), Base64.Encode(up), Base64.Encode(und), Base64.Encode(ufn), csurl1);
    //        Script.ShowAndRedirect(Page,"资源文件上传成功!进入资源添加界面!",url);
    //    }
    //    catch (Exception ex)
    //    {
    //        PowerCreator.LMS.Logic.Log.DBLog.AddDBExceptionLog(ex);
    //        Script.Alert(Page, "msg", "文件上传过程中出现异常!请查看数据库日志!");
    //        return;
    //    }       
    //}
    //private bool CheckNewFoladerName(string newFolderName)
    //{
    //    if (newFolderName.IndexOf("\\") !=-1)
    //    {
    //        Script.Alert(Page, "msg", "资源文件夹名称中不能包含 \\ 字符!请重新输入!");
    //        return false;            
    //    }
    //    if (newFolderName.IndexOf("/") != -1)
    //    {
    //        Script.Alert(Page, "msg", "资源文件夹名称不能包含 / 字符,请重新输入!");
    //        return false;
    //    }
    //    return true;

    //}
    //private bool CheckUploadFile()
    //{
    //    HttpPostedFile hpf = flResource.PostedFile;
    //    string fileName = GetFileName(hpf);
    //    if (string.IsNullOrEmpty(hpf.FileName))
    //    {
    //        Script.Alert(Page, "msg", "上传文件不能为空!");
    //        return false;
    //    }
    //    if (hpf.ContentLength == 0)
    //    {
    //        Script.Alert(Page, "msg", "上传文件不能为空!");
    //        return false;
    //    }

    //    int resourcetypeid = int.Parse(ddlResourceType.SelectedValue);
    //    int worked = GetWorked(resourcetypeid);
    //    if (worked == 1)
    //    {
    //        if (GetFileExtension(fileName).ToLower() != "rar")
    //        {
    //            Script.Alert(Page, "msg", "文件类型不正确，如果为课件点播类型，则必须上传rar类型的压缩文件,请重新选择!");
    //            return false;
    //        }    
    //    }

    //    if (!CheckFileType(fileName))
    //    {
    //        Script.Alert(Page, "msg", "上传课件不符合上传文件类型限制!");
    //        return false;
    //    }
    //    if (string.IsNullOrEmpty(ddlCourse.SelectedValue))
    //    {
    //        Script.Alert(Page,"msg","目前没有可选择的课程，请添加课程后再上传!");
    //        return false;
    //    }
    //    if (string.IsNullOrEmpty(ddlResourceType.SelectedValue))
    //    {
    //        Script.Alert(Page,"msg","没有上传文件类型，请添加上传文件类型!");
    //        return false;
    //    }

    //    return true;
    //}
    //private int GetWorked(int resourceTypeID)
    //{
    //    DataTable dt = new DataTable();
    //    string search = " TypeID = "+resourceTypeID.ToString();
    //    dt = resourectTypeManager.Query(search);

    //    return int.Parse(dt.Rows[0]["TypeID"].ToString());
    //}
    //private string GetFileExtension(string fileName)
    //{
    //    return fileName.Substring(fileName.LastIndexOf(".") + 1);
    //}
    //private string GetFileName(HttpPostedFile hpf)
    //{
    //    string fullName = hpf.FileName;
    //    string fileName = fullName.Substring(fullName.LastIndexOf("\\") + 1);
    //    return fileName;
    //}

    //private bool CheckFileType(string filePath)
    //{
    //    string fileExtension = GetFileExtension(filePath);
    //    string allowExtensions = ConfigurationManager.AppSettings["CourseUploadFile"].ToString();
    //    return FileUploaded.IsAllowedExtension(fileExtension,allowExtensions);
    //}

    //private void BinderCourse()
    //{
    //    DataTable dt = new DataTable();
    //    dt = courseManager.Query("");
    //    ddlCourse.DataSource = dt;
    //    ddlCourse.DataTextField = "CourseName";
    //    ddlCourse.DataValueField = "Course_Id";
    //    ddlCourse.DataBind();
    //}
    //private void BinderResourceType()
    //{
    //    DataTable dt = new DataTable();
    //    dt = resourectTypeManager.Query("");
    //    ddlResourceType.DataSource = dt;
    //    ddlResourceType.DataTextField = "TypeName";
    //    ddlResourceType.DataValueField = "TypeID";
    //    ddlResourceType.DataBind();
    //}
    //protected void btnBack_Click(object sender, EventArgs e)
    //{        
    //    Script.RedirectURL(csurl2);
    //}

    //private void WriteLog(string msg)
    //{
    //    log.WriteFile(msg, "UploadFile");
    //}

    protected void ddl_Course_SelectedIndexChanged(object sender, EventArgs e)
    {
        BuildDirectory();
    }
    protected void ddl_ResourceType_SelectedIndexChanged(object sender, EventArgs e)
    {
        BuildDirectory();
    }
}
